package controllers

import (
	"Trace/constant"
	"Trace/models"
	"Trace/utils"
	"encoding/json"
	"strconv"

	beego "github.com/beego/beego/v2/server/web"
)

type FoodController struct {
	beego.Controller
}

// 获取所有食品id
func (Trace *FoodController) GetAllFoods() {
	var foods [][]int
	body := utils.DoRequest(constant.ContractName, constant.ContractAdress, "getAllFood", constant.Abi, constant.ProducerAddress, make([]interface{}, 0))
	json.Unmarshal(body, &foods)
	Trace.Data["json"] = utils.Resp(200, "success", foods)
	Trace.ServeJSON()
}

// TODO Get /getFood 根据食品溯源id获取食品信息
func (Trace *FoodController) GetFood() {
	id, err := strconv.Atoi(Trace.Ctx.Input.Query("Id"))
	if err != nil {
		Trace.Data["json"] = utils.Resp(400, "invalid param", nil)
		Trace.ServeJSON()
		return
	}
	var FoodInfo models.FoodInfo
	param := []interface{}{id}
	body := utils.DoRequest(constant.ContractName, constant.ContractAdress, "getFood", constant.Abi, constant.ProducerAddress, param)
	json.Unmarshal(body, &FoodInfo)
	Trace.Data["json"] = utils.Resp(200, "success", FoodInfo)
	Trace.ServeJSON()

}

// 新建食品
func (Trace *FoodController) NewFood() {
	var foodinfo models.FoodInfoForms
	json.Unmarshal(Trace.Ctx.Input.RequestBody, &foodinfo)
	//TODO 参数校验 1、非空 2、范围
	// 1、后端做校验 2、合约层做校验
	//合约层：返回信息不一致 errorMessage || message
	//后端：麻烦

	// if err != nil || foodinfo.Name == "" || foodinfo.TraceName == "" {
	// 	Trace.Data["json"] = utils.Resp(400, "invalid param", nil)
	// 	Trace.ServeJSON()
	// 	return
	// }

	param := []interface{}{
		foodinfo.Name,
		foodinfo.TraceNumber,
		foodinfo.TraceName,
		foodinfo.Quality,
	}
	body := utils.DoRequest(constant.ContractName, constant.ContractAdress, "newFood", constant.Abi, constant.ProducerAddress, param)
	msg := utils.GetJsonVal(string(body), "message")
	errormsg := utils.GetJsonVal(string(body), "errorMessage")
	if errormsg != "" {
		Trace.Data["json"] = utils.Resp(400, "Fail", "invalid param")
		Trace.ServeJSON()
		return
	}
	if utils.GetJsonVal(string(body), "statusOK").(bool) {
		Trace.Data["json"] = utils.Resp(200, "Success", nil)
		Trace.ServeJSON(false)
		return
	} else {
		Trace.Data["json"] = utils.Resp(400, "Fail", msg)
		Trace.ServeJSON(false)
		return
	}

}
